<?php

/**
 * 内容展示
 * Class miContentShow
 */
class miContentShow
{
    public function __construct()
    {
        //
    }

    /**
     * 获取内容展示详情
     * @param $param /参数
     */
    static public function getMiContentShowById($param)
    {
        $retVal = Session::init();
        $uid = Session::$user['userId'];
        /*调试使用*/
        //$uid = Session::$user['userId'] = 420;
        $id=$param->id;
        $miUId=$param->miUId;
        $qId = $param->qId;
        $startUid = $param->miUId;
        Log::write('miContentShow|miuId:'.$miUId.'|qId:'.$qId.'|uid:'.$uid);
        if(!$miUId||!$qId){
            $quanInfo = Module::callModule("micontent", Session::$user,"isPartner",'');
            $qId = $quanInfo['qId'];
            $miUId = $quanInfo['uId'];
        }
        //初试化model类
        $customerId = Session::$user['customerId'];
        $allUserModel = D("user");
        Session::switchCustomer(0);
        $miContentModel = M("micontent_show");
        $quanUser_table = M('quan_user');
        $quan_tab = M('miyouquan');
        $contentRecommend_tabel = M('micontent_show_recommend');
        $bothContent_table = M('micontent_show_content');
        Session::switchCustomer($customerId);

        $where["a.id"]=array('eq',$id);
        $where["a.deleted"]=array('eq',0);
        $where["s.module"]=array('eq','miContentShow');
        $micon = $miContentModel->alias('a')
            ->join("left join wx_pb_template b on a.templateId=b.id")
            ->join("inner join wx_mishare s on s.moduleId=a.id")
            ->field("a.id,a.name,a.joinQuanId,a.joinQuanTip,a.shareTitle,a.shareDescription,a.sharePic,a.templateId,
                s.id as sId, b.tplname, b.module")
            ->where($where)
            ->find();

        if($uid){
            $userInfo = $allUserModel->alias('a')
                ->join('wx_'.$customerId.'_user_weixin_info b on a.id=b.userId')
                ->join('wx_mimall_user c on a.id=c.uId and c.cId='.$customerId)
                ->field('a.id, a.fullName, a.userName, b.nickName, b.headImgUrl,c.saleSource')
                ->where('a.id='.$uid)
                ->find();
            if($userInfo == null){
                Log::write('查询userInfo失败:'.$allUserModel->getLastSql());
            }
            $micon['userInfo'] = $userInfo;
            if(!$param->saleSource){
                $param->saleSource = $userInfo['saleSource'];
            }
        }
        //获取推荐文章列表
        $micon['recommendList'] = $contentRecommend_tabel->alias('a')
            ->join('inner join wx_micontent b on a.contentId = b.id and b.deleted = 0')
            ->where(['cid' => $customerId, 'contentShowId' => $micon['id']])
            ->field('b.id, b.title, b.bigPicUrl, b.picUrl, b.createTime')
            ->order('b.createTime desc')
            ->select();
        $customer = WeixinApi::getCustomer();
        if ($customer['mode'] && $customer['grantStatus']) {
            $domainName = $customer["appid"];
            $http['RESOURCEURL'] = "http://" . $domainName . "." . C('NEWSERVER_HOST');
        } else {
            $http['RESOURCEURL'] = C("SERVER_HOST");
        }
        if($micon['recommendList']){
            foreach($micon['recommendList'] as $key => $val){
                $val['link'] = $http['RESOURCEURL'] . 'call.html?customerId=' . $customerId . '&module=micontent&method=getMiContentDetail&params=%7B%22id%22:'.$val['id'].',%22miUId%22:'.$miUId.',%22qid%22:'.$qId.'%7D';
                $micon['recommendList'][$key] = $val;
            }
        }

        //获取关联内容标签
        $micon['contentTagArr'] = $bothContent_table->alias('a')
            ->join('inner join wx_micontent_tag b on a.contentTagId = b.id and b.fromCustomerId = '.$customerId)
            ->where(['a.cid' => $customerId, 'a.contentShowId' => $micon['id']])
            ->field('a.contentTagId as id, a.contentTagAlias, b.tagName')
            //->order('a.createTime desc')
            ->select();

        $micon['moduleId'] = $micon['id'];
        /*判断模板*/
        $templateType = 0;
        if($micon['module'] == 'miContentShow'){
            if($micon['tplname'] == '内容展示1'){
                $templateType = 1;
            }
        }
        $micon['templateType'] = $templateType?$templateType:1;
        $micon['isShowQuqnIco'] = 3;
        if($uid){
            $quanConfig = $quan_tab->where(['id'=>$qId])->getField('config');
            if($quanConfig){
                $micon['themeColor'] = json_decode($quanConfig,true)['reveal']['themeColor'];
            }
            $quanUserInfo = $quanUser_table->alias('u')
                ->join('inner join wx_miyouquan q on u.qid=q.id')
                ->where(['q.cId'=>$customerId, 'u.uid'=>$uid, 'u.deleted'=>0, 'u.status'=>1])
                ->field('u.qid as currentUserQid,q.name,q.logo,q.config')
                ->find();
            if($quanUserInfo !== null){
                if($uid == $startUid || empty($startUid)){  //此用户已经在圈子内,且和分享
                    $micon['isShowQuqnIco'] = 1;	//可进入圈
                    //获取来源圈子信息
                    $micon['quanLogo'] = $quanUserInfo['logo']?$quanUserInfo['logo']:'';
                    $micon['quanName'] = $quanUserInfo['name']?$quanUserInfo['name']:'';
                    if($quanUserInfo['config']){
                        $micon['themeColor'] = json_decode($quanUserInfo['config'],true)['reveal']['themeColor'];
                    }
                }else{      //当前用户是好友,但不是首次分享的好友, 不显示"我的"图标以及"加入"图标, 显示"我要分享"图标
                    $micon['isShowQuqnIco'] = 2;
                }
            }else if($micon['joinQuanId']){
                $micon['isShowQuqnIco'] = 0;	//可加入圈
            }
        }
        Log::write('miContentShow:'.$startUid.'-isShow:'.$micon['isShowQuqnIco'].'-uid:'.$uid);

        //添加访问记录
        if(!$param->miUId){
            $param->miUId = $uid;
        }
/*        if(!$param->saleSourceUId){
            $param->saleSourceUId = $uid;
        }*/
        if(!$param->qId){
            $param->qId = $qId;
        }
        Session::switchCustomer($customerId);
        $visitParam=new StdClass();
        $visitParam->sId=$micon["sId"];
        $visitParam->title=$micon["name"];
        $visitParam->miUId=$param->miUId;
        $visitParam->qId=$param->qId;
        $visitParam->fromPage="miContentShow_detail";
        $visitParam->cid=$customerId;
        $visitParam->visitId= $param->visitId;							//上一次浏览id
        $visitParam->lastShareUId= $param->lastShareUId;							//上一次浏览id
        $visitParam->saleSource= $param->saleSource;							//销售id
        $visitId = Module::callModule("quan", Session::$user,"addVisit", $visitParam);

        $micon["userName"]=Session::$user['userName'];
        $micon["visitId"]=$visitId;
        $micon['lastShareUId']=$uid;
        $micon['saleSource']=$param->saleSource;

        $micon["miUId"]=$miUId;
        $micon["userId"]=$uid;
        $micon["qId"]=$qId; //链接上的qid

        Session::switchCustomer($customerId);
        if (!$micon) {
            Output::instance()->object([
                'code' => -1,
                'msg' => '内容不存在',
                'data' => []
            ]);
            return;
        }

        Log::write('miContentShow|userId:'.$uid.'|miUId:'.$micon['miUId'].'|qId:'.$qId);
        Output::instance()->object($micon);
    }

    /**
     * 通过文章标签获取文章列表
     * @param $param /标签id
     */
    static public function getContentByTagId($param)
    {
        $retVal = Session::init();

        if(!$param->start){
            $param->start = 0;
        }
        if(!$param->limit){
            $param->limit = 10;
        }
        $miUId = $param->miUId;
        $qId = $param->qId;
        $cid = Session::$user['customerId'];;
        Session::switchCustomer(0);
        $micontent_table = M('micontent');
        Session::switchCustomer($cid);

        $where = [];
        /*if($title){
            $where['a.title'] = ['like', '%'.$title.'%'];
        }*/

        if($param->id){
            $where['b.tagId'] = $param->id;
        }
        $where['a.deleted'] = 0;
        $contentList = $micontent_table->alias('a')
            ->join('wx_micontent_tag_list b on a.id = b.webPageId and b.fromCustomerId='.$cid)
            ->field('a.id, a.title, a.createTime, a.bigPicUrl, a.picUrl, a.description')
            ->where($where)
            ->limit($param->start, $param->limit)
            ->order('a.createTime desc')
            ->select();
        //var_dump($micontent_table->getLastSql());
        if($contentList == null){
            Log::write('内容展示关联标签的内容不存在:'.$micontent_table->getLastSql());
            $massage = [
                'code' => 0,
                'msg' => '暂无文章',
                'total' => 0,
                'results' => []
            ];
            Output::instance()->object($massage);
            return;
        }

        $customer = WeixinApi::getCustomer();
        if ($customer['mode'] && $customer['grantStatus']) {
            $domainName = $customer["appid"];
            $http['RESOURCEURL'] = "http://" . $domainName . "." . C('NEWSERVER_HOST');
        } else {
            $http['RESOURCEURL'] = C("SERVER_HOST");
        }
        foreach($contentList as $key => $val){
            $val['link'] = $http['RESOURCEURL'] . 'call.html?customerId=' . $cid . '&module=micontent&method=getMiContentDetail&params=%7B%22id%22:'.$val['id'].',%22miUId%22:'.$miUId.',%22qid%22:'.$qId.'%7D';
            $contentList[$key] = $val;
        }

        $total = $micontent_table->alias('a')
            ->join('wx_micontent_tag_list b on a.id = b.webPageId and b.fromCustomerId='.$cid)
            ->where($where)
            ->count();
        $massage = [
            'code' => 0,
            'msg' => 'ok',
            'total' => $total,
            'results' => $contentList
        ];
        Output::instance()->object($massage);
    }
}